package com.tian.service.impl;

import com.tian.common.CommonResult;
import com.tian.dto.coupon.CouponUsedStatisticsRespDto;
import com.tian.mapper.CouponUsedStatisticsMapper;
import com.tian.service.CouponUsedStatisticsService;
import com.tian.util.RedisConstantPre;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-10-26 17:54
 * {@code @version:} 1.0
 */
@Service
public class CouponUsedStatisticsServiceImpl implements CouponUsedStatisticsService {
    @Resource
    private CouponUsedStatisticsMapper couponUsedStatisticsMapper;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public CommonResult<CouponUsedStatisticsRespDto> getCouponUsedStatistics(Integer couponId) {
        //统计每个优惠券被使用次数
        RAtomicLong atomicLong = redissonClient.getAtomicLong(RedisConstantPre.COUPON_GET_COUNT_PRE + couponId);
        CouponUsedStatisticsRespDto couponUsedStatisticsRespDto = couponUsedStatisticsMapper.countByCouponId(couponId);

        if (couponUsedStatisticsRespDto == null) {
            couponUsedStatisticsRespDto = new CouponUsedStatisticsRespDto();
            couponUsedStatisticsRespDto.setCouponId(couponId);
            couponUsedStatisticsRespDto.setCountUsed(0);
            couponUsedStatisticsRespDto.setDiscountTotalAmount(BigDecimal.ZERO);
        }
        couponUsedStatisticsRespDto.setCountGet(atomicLong.get());
        return CommonResult.success(couponUsedStatisticsRespDto);
    }
}
